package com.corx.network.core.listener;

import com.corx.network.core.model.ReceivedMessage;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.nio.charset.StandardCharsets;


public class MyListener extends ReceivedMessageListener<ReceivedMessage, ReceivedMessage> {

    private static final Logger log = LoggerFactory.getLogger(MyListener.class);

    @Override
    protected ReceivedMessage doHandler(ReceivedMessage message) {

        try {
            String raw = new String(message.getPayload(), StandardCharsets.UTF_8);
            log.info("进入了MyListener方法，payload：翻译成String：{}",raw);

            // 解析成对象再转成标准 JSON
            ObjectMapper objectMapper = new ObjectMapper();
            // 可转 Map、List 等
            Object jsonObject = objectMapper.readValue(raw, Object.class);
            // 格式化成标准 JSON 字符串
            String formattedJson = objectMapper.writeValueAsString(jsonObject);
            message.setTranslatedPayload(formattedJson);
            log.info("进入了MyListener方法，payload：翻译成json字符串，setTranslatedPayload设置为：{}",raw);
        } catch (Exception e) {
            log.error("Payload 转 JSON 失败，setTranslatedPayload设置为空//{//}对象", e);
            message.setTranslatedPayload("{}");
        }
        return message;
    }


}
